package com.lcc.lynx.jdbc.handle;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * BigDecimal 类型处理器 去除多余的 0
 * @author lcc
 * @date 2025/6/27 14:06
 */
@MappedJdbcTypes(JdbcType.DECIMAL)
@MappedTypes(BigDecimal.class)
public class DecimalTypeHandler extends BaseTypeHandler<BigDecimal> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setBigDecimal(i, parameter);
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, String columnName) throws SQLException {
        BigDecimal value = rs.getBigDecimal(columnName);
        if (value != null) {
            return new BigDecimal(value.stripTrailingZeros().toPlainString());
        }
        return null;
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        BigDecimal value = rs.getBigDecimal(columnIndex);
        if (value != null) {
            return new BigDecimal(value.stripTrailingZeros().toPlainString());
        }
        return null;
    }

    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        BigDecimal value = cs.getBigDecimal(columnIndex);
        if (value != null) {
            return new BigDecimal(value.stripTrailingZeros().toPlainString());
        }
        return null;
    }

}